package com.gudy.counter.filter;

import com.google.common.collect.Sets;
import com.gudy.counter.service.AccountSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Component
public class SessionCheckFileter  implements Filter {

    @Autowired
    private AccountSerivce accountSerivce;
    //白名单
    private Set<String> whiteRootPaths = Sets.newHashSet("login","msgsocket","test","websocket");

    @Override
     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //解决ajax跨域问题
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //'Content-type': 'application/x-www-form-urlencoded'
        response.setHeader("Access-Control-Allow-Origin","*");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String pathUrl = httpServletRequest.getRequestURI();
        String[] splitPath = pathUrl.split("/");
        if (splitPath.length < 2){
            httpServletRequest.getRequestDispatcher("login/loginfaile").forward(servletRequest,servletResponse);
        }else{
            if (whiteRootPaths.contains(splitPath[1])){
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //不在白名单验证token是否合法
                if (accountSerivce.checkAccountExisInCache(httpServletRequest.getParameter("token"))){
                    filterChain.doFilter(servletRequest,servletResponse);
                }else{
                    httpServletRequest.getRequestDispatcher("login/loginfaile").forward(servletRequest,servletResponse);
                }
            }

        }

    }


}
